package com.karst.essentials.chapter10
{
	import caurina.transitions.Tweener;
	
	import org.papervision3d.core.geom.Particles;
	import org.papervision3d.core.geom.renderables.Particle;
	import org.papervision3d.events.InteractiveScene3DEvent;
	import org.papervision3d.materials.special.MovieAssetParticleMaterial;
	import org.papervision3d.objects.primitives.Sphere;

	internal class MovieAssetParticleMaterialExample extends ParticleTemplate
	{
		public function MovieAssetParticleMaterialExample()
		{
			super();
		}
		
		private var particlesArr : Array = [] ;
		private var sphere : Sphere = null ;
		override protected function createView():void
		{
			super.createView() ;
			if( sphere == null )
				sphere = new Sphere( null, 500, 10, 10 ) ;
			
			var material : MovieAssetParticleMaterial = 
				new MovieAssetParticleMaterial( AnimatedParticle ) ;
			material.smooth = true ;
			material.animated = true ;
			/**
			 * 交互性
			 */
			material.interactive = true ;
			
			
			numOfPartices = sphere.geometry.vertices.length ;
			for( var i : int = 0 ; i < numOfPartices; i++ )
			{
				var particles : Particles = new Particles() ;
				var particle : Particle = new Particle( material, 1 ) ;
				particles.addEventListener( InteractiveScene3DEvent.OBJECT_CLICK, clickHandler ) ;
				
				particles.addParticle( particle ) ;
				scene.addChild( particles ) ;
				particlesArr.push( particles ) ;
			}
			
			positionParticlesOnSphere() ;
		}

		private function positionParticlesOnSphere() : void
		{
			for( var i : int = 0 ; i < numOfPartices ; i++ )
			{
				Tweener.addTween( particlesArr[i],
					{ 
					  x : sphere.geometry.vertices[i].x, 
					  y : sphere.geometry.vertices[i].y, 
					  z : sphere.geometry.vertices[i].z, 
					  time : 1, 
					  transition : "easeOutBack" 
					}
					) ;
			}
		}

		private function positionParticlesRandomly() : void
		{
			for( var i : int = 0 ; i < numOfPartices ; i++ )
			{
				Tweener.addTween( particlesArr[i],
					{ 
					  x : randPos(), 
					  y : randPos(), 
					  z : randPos(), 
					  time : 3, 
					  transition : "easeInOutElastic" 
					}
					) ;
			}
		}
		
		
		
		private var randMode : Boolean = false ;
		private function clickHandler( $event : InteractiveScene3DEvent ) : void
		{
			if( randMode )
			{
				positionParticlesOnSphere() ;
				randMode = false ;
			}
			else
			{
				positionParticlesRandomly() ;
				randMode = true ;
			}
		}
	}
}